package org.mtmi.ui.controls;

import java.util.ArrayList;

import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.mtmi.ui.M;
import org.mtmi.ui.controls.listeners.ControlDisposedListener;
import org.mtmi.ui.controls.listeners.DisposeEvent;
import org.mtmi.ui.controls.listeners.MenuSelectionListener;
import org.mtmi.ui.scenes.COLOR;
import org.mtmi.ui.scenes.Scene;

public class Int16Menu 
{

	private FlowerMenu menu;
	private ArrayList<MenuSelectionListener> lis_menu;
	private Scene scene;
	private int   flags;
	private Color bg, fg, tx;
	
	public Int16Menu( Scene s, int _flags ) {
		scene = s;
		flags = _flags;
		bg = COLOR.grey0;
		fg = COLOR.grey100;
		tx = COLOR.grey60;
	}
	
	public void setForeground( Color c ) { fg=c; if( !isDisposed() ) menu.setForeground( c ); }
	public void setBackground( Color c ) { bg=c; if( !isDisposed() ) menu.setBackground( c ); }
	public void setTextColor( Color c ) { tx=c; if( !isDisposed() ) menu.setTextColor( c ); }
	
	/** open menu centered on control bounds */
	public void open( IVisualControl c ) {
		Point l = c.getLocation();
		Point s = c.getSize();
		open( l.x+s.x/2, l.y+s.y/2 );
	}
	
	public boolean isDisposed() { return menu== null || menu.isDisposed(); }
	
	public void close() {
		if( menu!=null && !menu.isDisposed() ) {
			menu.close();
		}
	}
	
	public void open( int x, int y ) {
		if( menu!=null ) return ;
		
		menu = new FlowerMenu( scene, flags & M.SCENE_EDITOR_CONTROL );
		if( bg!=null ) menu.setBackground( bg );
		if( fg!=null ) menu.setForeground( fg );
		if( tx!=null ) menu.setTextColor( tx );
		for( int i=1; i<=16; i++ ) {
			menu.addItem( Integer.toString(i), i );
		}
		menu.open( x, y );
		menu.addMenuSelectionListener( new MenuSelectionListener() {
			@Override
			public void menuEntrySelected(int id) {
				fireMenuItem( id );
				menu=null;
			}
		});
		menu.addControlDisposedListener( new ControlDisposedListener()  {
			@Override
			public void controlDisposed(DisposeEvent event) {
				menu=null;
			}
		});
	}
	
	public void addMenuSelectionListener( MenuSelectionListener lis ) {
		if( lis_menu==null ) {
			lis_menu = new ArrayList<MenuSelectionListener>();
		}
		lis_menu.add( lis );
	}
	
	public void removeMenuSelectionListener( MenuSelectionListener lis ) {
		if( lis_menu!=null ) {
			lis_menu.remove( lis );
		}
	}

	private void fireMenuItem( int id ) {
		if( lis_menu==null ) return ;
		MenuSelectionListener ls[] = lis_menu.toArray( new MenuSelectionListener[0] );
		for( int i=0; i<ls.length; i++ ) {
			ls[i].menuEntrySelected( id );
		}
	}

	
}
